﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

namespace Infrastructure.WebApi
{
    public class CacheGetMiddleware
    {
        private readonly RequestDelegate _next;
        public CacheGetMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            var isNeedSetCahce = false;
            var key = $"Cache:{httpContext.Request.Path}:{httpContext.Request.QueryString}";
            if (httpContext.Request.Method == "GET")
            {
                var endPoint = httpContext.Features.Get<IEndpointFeature>()?.Endpoint;
                if (endPoint != null && endPoint.Metadata.GetMetadata<CacheAttribute>() != null)
                {
                    var value = await RedisHelper.GetAsync(key);
                    if (value == null)
                    {
                        isNeedSetCahce = true;
                    }
                    else
                    {
                        httpContext.Response.ContentType = "application/json;charset=utf-8";
                        await httpContext.Response.WriteAsync(value);
                        return;
                    }
                }
            }
            Stream responseBodyStream = httpContext.Response.Body;
            if (isNeedSetCahce)
            {
                using (var memStream = new MemoryStream())
                {
                    httpContext.Response.Body = memStream;
                    await _next(httpContext);
                    #region 返回
                    memStream.Position = 0;
                    string responseBody = new StreamReader(memStream).ReadToEnd();
                    await RedisHelper.SetAsync(key, responseBody, 2);
                    #endregion
                    memStream.Position = 0;
                    await memStream.CopyToAsync(responseBodyStream);
                }
            }
            else
            {
                await _next(httpContext);
            }
        }
    }
    /// <summary>
    /// 缓存标记
    /// </summary>
    public class CacheAttribute : Attribute
    {

    }
}
